<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { ref, reactive, computed } from 'vue';
import { confirm, DocAlert, Page, useVbenDrawer } from '@vben/common-ui';
import {
    Form,
    FormItem,
    Input,
    InputNumber,
    Select,
    TimePicker,
    Switch,
    message,
} from 'ant-design-vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import Form1 from './modules/form.vue';

import type { SysAbsenceRuleApi } from '#/api/moxi/sysabsencerule';
import {
    getSysAbsenceRulePage,
    createSysAbsenceRule,
    updateSysAbsenceRule,
    deleteSysAbsenceRule,
} from '#/api/moxi/sysabsencerule';

const rulesTitle = ref<string>();
const open = ref<boolean>(false);
// 创建表单引用
const formRef = ref();
// 表单数据
const formData = reactive({
    id: undefined,
    startTime: '',
    endTime: '',
    absenceThreshold: undefined,
    status: 1,
    ruleAlias: '',
    ruleDesc: '',
});
const rules = {
    startTime: [{ required: true, message: '请选择开始时间' }],
    endTime: [{ required: true, message: '请选择结束时间' }],
    absenceThreshold: [{ required: true, message: '请输入违规临界值' }],
    status: [{ required: true, message: '请选择状态' }],
    ruleAlias: [{ required: true, message: '请输入别名' }],
};
// 创建
const showModal = () => {
    open.value = true;
     Object.assign(formData, {
        id: undefined,
        startTime: '',
        endTime: '',
        absenceThreshold: undefined,
        status: 1,
        ruleAlias: '',
        ruleDesc: '',
    });
    rulesTitle.value = '创建规则';
};
const handleOk = async (e: MouseEvent) => {
    console.log(e);
    try {
        console.log('表单数据:', formData);
        const valid = await formRef.value.validate();
        if (valid) {

            let res = await (formData.id
                ? updateSysAbsenceRule(formData)
                : createSysAbsenceRule(formData));
            console.log('创建结果:', res);
            if (res) {
                open.value = false;
                message.success('保存成功');
                // 重置表单
                Object.assign(formData, {
                    id: undefined,
                    startTime: '',
                    endTime: '',
                    absenceThreshold: undefined,
                    status: 1,
                    ruleAlias: '',
                    ruleDesc: '',
                });
                onRefresh();
            } else {
                message.error('保存失败');
            }
        }
    } catch (error) {
        console.error('保存失败:', error);
    }
};
// 编辑
async function handleUpdate(row: SysAbsenceRuleApi.SysAbsenceRule) {
    try {
        rulesTitle.value = '编辑规则';
        Object.assign(formData, {
            id: row.id,
            startTime: row.startTime || '',
            endTime: row.endTime || '',
            absenceThreshold: row.absenceThreshold,
            status: row.status,
            ruleAlias: row.ruleAlias || '',
            ruleDesc: row.ruleDesc || '',
        });
        // 打开弹窗
        open.value = true;
    } catch (error) {
        console.log(error);
    }
}



const [FormDrawer, formDrawerApi] = useVbenDrawer({
    connectedComponent: Form1,
    destroyOnClose: true,
});

/** 刷新表格 */
function onRefresh() {
    gridApi.query();
}

/** 选择摄像头 */
function handleEdit(row: SysAbsenceRuleApi.SysAbsenceRule) {
    console.log($t('common.edit'));
    formDrawerApi.setData(row).open();
}

const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
    records,
}: {
    records: SysAbsenceRuleApi.SysAbsenceRule[];
}) {
    checkedIds.value = records.map((item) => item.id as number);
}

const [Grid, gridApi] = useVbenVxeGrid({
    formOptions: {
        schema: useGridFormSchema(),
    },
    gridOptions: {
        columns: useGridColumns(),
        height: 'auto',
        keepSource: true,
        proxyConfig: {
            ajax: {
                query: async ({ page }, formValues) => {
                    return await getSysAbsenceRulePage({
                        pageNo: page.currentPage,
                        pageSize: page.pageSize,
                        ...formValues,
                    });
                },
            },
        },
        rowConfig: {
            keyField: 'id',
            isHover: true,
        },
        toolbarConfig: {
            refresh: { code: 'query' },
            search: true,
            slots: { tools: 'toolbarButtons' },
        },
    } as VxeTableGridOptions<SysAbsenceRuleApi.SysAbsenceRule>,
    gridEvents: {
        checkboxAll: handleRowCheckboxChange,
        checkboxChange: handleRowCheckboxChange,
    },
});

// 删除
async function handleDelete(row: SysAbsenceRuleApi.SysAbsenceRule) {
    try {
        const res = await deleteSysAbsenceRule(row.id as number);
        if (res) {
            message.success('删除成功');
            onRefresh();
        } else {
            message.error('删除失败');
        }
    } catch (error) {
        console.log(error);
    }
}
</script>

<template>
    <Page auto-content-height>
        <FormDrawer @success="onRefresh" />
        <!-- auth: ['system:user:update'], -->
        <Grid table-title="规则列表">
            <template v-slot:toolbarButtons>
                <a-button type="primary" @click="showModal">创建</a-button>
            </template>
            <template #actions="{ row }">
                <TableAction :actions="[
                    {
                        label: $t('common.edit'),
                        type: 'link',
                        icon: ACTION_ICON.EDIT,
                        onClick: handleUpdate.bind(null, row),
                    },
                    {
                        label: $t('common.delete'),
                        type: 'link',
                        danger: true,
                        icon: ACTION_ICON.DELETE,
                        popConfirm: {
                            title: $t('ui.actionMessage.deleteConfirm', [row.ruleAlias]),
                            confirm: handleDelete.bind(null, row),
                        },
                    },
                    {
                        label: '选择摄像头',
                        type: 'link',
                        icon: ACTION_ICON.EDIT,
                        onClick: handleEdit.bind(null, row),
                    },
                ]" />
            </template>
        </Grid>
        <a-modal v-model:open="open" :title="rulesTitle" @ok="handleOk" width="600px">
            <Form ref="formRef" :model="formData" :rules="rules" layout="vertical" style="margin-top: 20px;"
                :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }">
                <FormItem label="开始时间" name="startTime">
                    <TimePicker v-model:value="formData.startTime" placeholder="请选择开始时间" format="HH:mm:ss"
                        value-format="HH:mm:ss" style="width: 100%" />
                </FormItem>

                <FormItem label="结束时间" name="endTime">
                    <TimePicker v-model:value="formData.endTime" placeholder="请选择结束时间" format="HH:mm:ss"
                        value-format="HH:mm:ss" style="width: 100%" />
                </FormItem>

                <FormItem label="违规临界值（分钟）" name="absenceThreshold">
                    <InputNumber v-model:value="formData.absenceThreshold" placeholder="请输入违规临界值" :min="1"
                        style="width: 100%" />
                </FormItem>

                <FormItem label="状态" name="status">
                    <Select v-model:value="formData.status" placeholder="请选择状态">
                        <Select.Option :value="0">关闭</Select.Option>
                        <Select.Option :value="1">开启</Select.Option>
                    </Select>
                </FormItem>

                <FormItem label="别名" name="ruleAlias">
                    <Input v-model:value="formData.ruleAlias" placeholder="请输入别名" />
                </FormItem>

                <FormItem label="描述" name="ruleDesc">
                    <Input.TextArea v-model:value="formData.ruleDesc" placeholder="请输入描述" :rows="3" />
                </FormItem>
            </Form>
        </a-modal>
    </Page>
</template>
